//
//  HMNetworkTools.swift
//  06-Swift-AFN 网络封装
//
//  Created by Apple on 16/10/23.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import AFNetworking
// get post 请求方式枚举(Swift 枚举写法)
enum HMNetworkToolsMethod: String {
    case get = "get"
    case post = "post"
}

class HMNetworkTools: AFHTTPSessionManager {
    // 全局访问点
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        // 反序列化格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    /// 网络请求公共方法
    ///
    /// - parameter method:     请求方式
    /// - parameter urlString:   url 地址
    /// - parameter parameters: 请求参数
    /// - parameter success:    成功
    /// - parameter failure:    失败
    func requet(method: HMNetworkToolsMethod, urlString: String, parameters: Any?, success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        // 如果是 get 请求
        if method == .get {
            get(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) in
                success(responseObject)
                }, failure: { (_, error) in
                    failure(error)
            })
        }else {
            // post 请求
            post(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) in
                success(responseObject)
                }, failure: { (_, error) in
                    failure(error)
            })
        }
        
    }
}

//  MARK: - 发微博相关接口
extension HMNetworkTools {
    
    
    
    //  发送带图片的微博接口
    ///
    /// - parameter access_token: 访问令牌
    /// - parameter status:       微博内容
    /// - parameter image:        上传的图片
    /// - parameter success:      成功回调的闭包
    /// - parameter failure:      失败回调的闭包
    func upload(access_token: String, status: String, image: UIImage, success:@escaping (Any?)->(), failure:@escaping (Error)->()) {
        //  请求接口地址
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        //  请求参数
        let params = [
            "access_token": access_token,
            "status": status
        ]
        
        //  图片转成二进制
        //
        //let imageData = UIImagePNGRepresentation(image)!
        //  compressionQuality 表示图片的质量系统, 取值范围0-1之前, 系统越大图片质量越大,否则就不够清晰
        let imageData = UIImageJPEGRepresentation(image, 0.5)!
        //  把二进制数据写到指定路径上
        //(imageData as NSData).write(toFile: "/Users/apple/Desktop/2.png", atomically: true)
        
        
        post(url, parameters: params, constructingBodyWith: { (formData) in
            formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/png")
            }, progress: nil, success: { (_, response) in
                success(response)
            }) { (_, error) in
                failure(error)
        }
    
    }
    
    //  发送文字微博
    func update(access_token: String, status: String, success:@escaping (Any?)->(), failure:@escaping (Error)->()) {
        //  请求接口地址
        let url = "https://api.weibo.com/2/statuses/update.json"
        //  请求参数
        let params: [String: Any] = [
            "access_token": access_token,
            "status": status
        ]
        //  执行 post 网络请求
        requet(method: .post, urlString: url, parameters: params, success: success, failure: failure)
        
        
    }
    
    
    

}



// MARK: - 首页相关接口
extension HMNetworkTools {
    func homeLoadData(sinceId: Int64, maxId: Int64, success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        // 请求 url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // 请求参数
        let params: [String: Any] = [
            "access_token": HMUserAccountViewModel.sharedTools.accessToken!,
            "since_id":sinceId,
            "max_id":maxId
        ]

        print(urlString + "?access_token=\(HMUserAccountViewModel.sharedTools.accessToken!)")
        
        
        // 发送请求
        requet(method: HMNetworkToolsMethod.get, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}

// MARK: - OAuth 授权相关接口
extension HMNetworkTools {
    // 获取 userAccount
    func oauthLoadUserAccount(code: String, success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        // 请求 urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id": HMAPPKEY,
            "client_secret": HMAPPSECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": HMREDIRECTURI
        ]
        // 发送请求
        requet(method: HMNetworkToolsMethod.post, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    
    // 请求用户信息
    func oauthLoadUserInfo(model: HMUserAccountModel, success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        // 请求 urlString
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token":model.access_token!,
            "uid":model.uid!
        ]
        // 发送请求
        requet(method: HMNetworkToolsMethod.get, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}
